import dotenv from 'dotenv';

// 加载环境变量
dotenv.config();

// 必需的环境变量
const requiredEnvVars = [
  'DB_HOST',
  'DB_PORT',
  'DB_USER',
  'DB_PASSWORD',
  'DB_NAME',
  'JWT_SECRET',
  'JWT_EXPIRES_IN',
  'MINIPROGRAM_API_PORT',
  'ADMIN_API_PORT',
  'UPLOAD_DIR',
  'MAX_FILE_SIZE'
];

// 验证环境变量
export const validateEnv = (): void => {
  const missingEnvVars = requiredEnvVars.filter(
    (envVar) => !process.env[envVar]
  );

  if (missingEnvVars.length > 0) {
    throw new Error(
      `缺少必需的环境变量: ${missingEnvVars.join(', ')}`
    );
  }

  // 验证端口号
  const ports = ['MINIPROGRAM_API_PORT', 'ADMIN_API_PORT'];
  ports.forEach((port) => {
    const portNum = parseInt(process.env[port] || '');
    if (isNaN(portNum) || portNum < 1 || portNum > 65535) {
      throw new Error(`无效的端口号: ${process.env[port]}`);
    }
  });

  // 验证文件大小
  const maxFileSize = parseInt(process.env.MAX_FILE_SIZE || '');
  if (isNaN(maxFileSize) || maxFileSize <= 0) {
    throw new Error(`无效的文件大小限制: ${process.env.MAX_FILE_SIZE}`);
  }

  console.log('环境变量验证通过');
}; 